package cz.via.facepalm.calendar;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.TimePicker;
import cz.via.facepalm.shared.CActivity;
import cz.via.facepalm.shared.CUser;
import cz.via.facepalm.shared.CUserActivity;

public class CalendarActivity extends Activity 
{
	CUser user;
	ProgressDialog progress2;
	int activity_id;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) 
	{		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activities_review);
		
		CUser u = (CUser)(getIntent().getExtras().getSerializable("user"));
		if(u==null){
			throw new RuntimeException("Hacking attempt exception");
		}
		this.user = u;
		TextView cred = (TextView) findViewById(R.id.credentials);
		cred.setText("user "+u.getName());
		
	    Button btn = (Button) findViewById(R.id.context_btn);  
	    registerForContextMenu(btn);
	    
	    Button newBtn = (Button) findViewById(R.id.new_activity_btn);
	    newBtn.setOnClickListener(new View.OnClickListener() 
		{
			public void onClick(View v) 
			{
				final Dialog dialog = new Dialog(CalendarActivity.this);
				dialog.setContentView(R.layout.newactivity);
				dialog.setTitle("New Activity");
				dialog.setCancelable(true);
				
				Button save = (Button) dialog.findViewById(R.id.save_activity_btn);
				save.setOnClickListener(new View.OnClickListener() 
				{
					public void onClick(View v) 
					{
						CActivity activity = new CActivity();
						EditText titleInput = (EditText)dialog.findViewById(R.id.title);
						String title = titleInput.getText().toString();												
						activity.setName(title);
						DatePicker date = (DatePicker) dialog.findViewById(R.id.datePicker);												
						GregorianCalendar calendar = new GregorianCalendar(date.getYear(),date.getMonth(),date.getDayOfMonth());
						int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
						TimePicker startT = (TimePicker) dialog.findViewById(R.id.startTimePicker);
						TimePicker endT = (TimePicker) dialog.findViewById(R.id.endTimePicker);
						
						ActivityHelper.setWeeklyTime(activity, dayOfWeek, 
													 startT.getCurrentHour(), startT.getCurrentMinute(), 
													 endT.getCurrentHour(), endT.getCurrentMinute());																		
						
						final ProgressDialog progress = ProgressDialog.show(CalendarActivity.this, "",
								"Sending",true);
						ServerComunicator.createActivity(activity,new DoneCallback<Void>() {
							@Override
							public void done(Void v) {	
								System.out.println("New activity was saved");
								progress.dismiss();
								dialog.dismiss();								
								updateList();
							}
						});
				
					}
				});
				
				Button cancelBtn = (Button) dialog.findViewById(R.id.cancel_newactivity_btn);
				cancelBtn.setOnClickListener(new View.OnClickListener() 
				{
					public void onClick(View v) 
					{
						dialog.dismiss();
					}
				});
				
				dialog.show();				
			}
		});
	    
	    updateList();	      
	}
	
	public void subscribeClickHandler(View v) 
    {    	      	    	
    	LinearLayout parentRow = (LinearLayout)v.getParent();    	 		
    	TextView IDString = (TextView)parentRow.getChildAt(0);    	    	
    	
    	final ProgressDialog progress3 = ProgressDialog.show(CalendarActivity.this, "",
				"Subscribing",true);
		activity_id = Integer.parseInt((String)IDString.getText());
		
		TextView stateView = (TextView)parentRow.getChildAt(1);
		final String state_id = (String)stateView.getText();
		
		if(state_id=="unsubscribed")
		{			
			System.out.println("subscribe");			
			ServerComunicator.subscribeToActivity(user.getId(),activity_id,new DoneCallback<Void>() {
				@Override
				public void done(Void v) {	
					System.out.println("Subscribed");
					progress3.dismiss();
					
					Intent intent = new Intent(CalendarActivity.this,
							ActivityDetail.class);
			    	Bundle credentials = new Bundle();							
					credentials.putSerializable("user", CalendarActivity.this.user);
					credentials.putLong("activityId", activity_id);
					intent.putExtras(credentials);
					startActivity(intent);
				}
			});			
		}
		else
		{
			
			System.out.println("unsubscribe");
			ServerComunicator.unSubscribeToActivity(user.getId(),activity_id,new DoneCallback<Void>() {
				@Override
				public void done(Void v) {						
					progress3.dismiss();
					updateList();
				}
			});	
		}
    	
    }
	
	protected void updateList()
	{		
		CalendarActivity.this.runOnUiThread(new Runnable() {
	        public void run() {
				 progress2 = ProgressDialog.show(CalendarActivity.this, "",
						"Downloading",true);
	        }
	    });
	    
	    ServerComunicator.listActivities(new DoneCallback<List<CActivity>>(){
			@Override
			public void done(final List<CActivity> allActivitis) 
			{	
				ServerComunicator.listUserActivities(user.getId(), new DoneCallback<List<CUserActivity>>() {
					
					@Override
					public void done(List<CUserActivity> userActivities) {
						
						final List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
					    for(CActivity a : allActivitis)
					    {
					    	Boolean found = false;
					    	for(CUserActivity cua : userActivities)
					    	{
					    		long id1 = cua.getIdActivity().getId();
					    		long id2 = a.getId();
					    		if(id1 == id2){
					    			found = true;
					    			break;
					    		}
					    	}					    			    
					    	
					    	HashMap<String, String> map = new HashMap<String, String>();
					    	map.put("name", a.getName());
					    	map.put("id", a.getId()+"");
					    	if(found) map.put("state","subscribed");
					    	else map.put("state","unsubscribed");
					    	fillMaps.add(map);
					    }	    
					    
					    CalendarActivity.this.runOnUiThread(new Runnable() {
					        public void run() {
					        	String[] from = new String[] {"id","name","state"};
					    		int[] to = new int[] {R.id.activity_id ,R.id.activity_name,R.id.state_id_text};
					    		
					    		ListView activityList = (ListView)findViewById(R.id.activity_list);
					    		activityList.setItemsCanFocus(true);
					    		final SimpleAdapter source = new SimpleAdapter(CalendarActivity.this, fillMaps,
					    				R.layout.activity_row,from, to);			    					    					    		
					    		activityList.setAdapter(source);			    				   
					    		
					    		source.notifyDataSetChanged();
					    		progress2.dismiss();
					        }
					    });
							
					}
				});
							
			    
			}
		});	
	}
	
	@Override  
    public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) 
    {  
    	super.onCreateContextMenu(menu, v, menuInfo);  
	    menu.setHeaderTitle("Actions");  
	    menu.add(0, v.getId(), 0, "Activity Detail");  	     
    }
	
	@Override  
	public boolean onContextItemSelected(MenuItem item) 
	{  
	    if(item.getTitle()=="Activity Detail"){
	    	Intent intent = new Intent(CalendarActivity.this,
					ActivityDetail.class);
	    	Bundle credentials = new Bundle();							
			credentials.putSerializable("user", this.user);
			intent.putExtras(credentials);
			startActivity(intent);
	    }  
	    
	    else return false;  
	    return true;  
	}  
}